<template>
	<view>
		<view class="page__content">
			<up-navbar :fixed="false" :title="pageConfig.titleName" :autoBack="true" :safeAreaInsetTop="true"
				leftIconColor="#fff">
			</up-navbar>

			<view class="page__content__main">

				<view class="common__box__form">
					<view class="common__box__form__card">
						<view class="common__box__form__card__title">
							<text>No:{{formData.BillNO}}</text>
						</view>

						<view class="common__box__form__card__field">
							<text class="common__box__form__card__field__label">产品信息：</text>
							<view class="common__box__form__card__field__value">
								<text>{{formData.ProductCode + '__' + formData.ProductName}}</text>
							</view>
						</view>

						<view class="common__box__form__card__field">
							<text class="common__box__form__card__field__label">产品规格：</text>
							<view class="common__box__form__card__field__value">
								<text>{{formData.ProductSpec}}</text>
							</view>
						</view>

						<view class="x-f">
							<view class="common__box__form__card__field">
								<text class="common__box__form__card__field__label">样品数：</text>
								<view class="common__box__form__card__field__value">
									<text>{{formData.BJNum}}</text>
								</view>
							</view>
							<view class="common__box__form__card__field">
								<text class="common__box__form__card__field__label">抽检数：</text>
								<view class="common__box__form__card__field__value">
									<text>{{formData.CJNum}}</text>
								</view>
							</view>
							<view class="common__box__form__card__field">
								<text class="common__box__form__card__field__label">拒收数：</text>
								<view class="common__box__form__card__field__value">
									<text>{{formData.RejectionNum}}</text>
								</view>
							</view>
						</view>

						<view class="common__box__form__card__field">
							<text class="common__box__form__card__field__label">负责人员：</text>
							<view class="common__box__form__card__field__value">
								<text>{{formData.CuratorName}}</text>
							</view>
						</view>

						<view class="common__box__form__card__field">
							<text class="common__box__form__card__field__label">检验方案：</text>
							<view class="common__box__form__card__field__value">
								<text>{{formData.ProjectName}}</text>
							</view>
						</view>

						<template v-if="formData.TestEndTime">
							<view class="common__box__form__card__field">
								<text class="common__box__form__card__field__label">检验期限：</text>
								<view class="common__box__form__card__field__value">
									<text>{{formData.TestEndTime}}</text>
								</view>
							</view>
						</template>




					</view>
				</view>


				<view style="padding: 7rpx 15rpx 15rpx;">
					<view class="child-card" v-for="(item, index) in tableData" :key="item.LabTestProductDeID">
						<!-- 顶部信息 -->
						<view class="child-card-top">
							<view class="child-card-top__left">
								<view class="ordinal">{{ index + 1 }}</view>
								<view class="title">{{ item.LabTestPlanContent }}</view>
							</view>
						</view>

						<!-- 检验轮次组 -->
						<view class="sample-list" v-if="item.Details && item.Details.length">

							<view class="sample-box" @click="openReportTable(sample)"
								v-for="(sample, sIndex) in item.Details" :key="sIndex">
								<view class="sample-header x-f">
									<!-- 折叠控制按钮 -->
									<view class="toggle-btn"
										@click.stop="toggleCollapse(sample.LabTestProductItemDeID +'_' +sample.LabTestProjectID)">
										{{ collapseStatus[sample.LabTestProductItemDeID +'_' +sample.LabTestProjectID] ? '展开' : '收起' }}
									</view>


									<text style="margin-left: 10rpx;">{{ sample.LabTestProjectName }}</text>
									<u-tag :text="sample.Result" style="margin-left: 10px;"
										:type="sample.FResult == 1 ? 'success' : sample.FResult == 0 ? 'error' : 'warning'"
										size="mini"></u-tag>

								</view>

								<template v-if="sample.ResultList.length">


									<view @click.stop="openMoreListTablePopup(sample)" class="readMore"
										v-if="sample.ResultList.length > 3">
										<text>查看更多>></text>
									</view>

									<!-- 样品检验结果表格 -->
									<uni-table border stripe emptyText="暂无更多数据"
										v-if="!collapseStatus[sample.LabTestProductItemDeID +'_' +sample.LabTestProjectID]">
										<!-- 表头行 -->
										<uni-tr>
											<uni-th align="left" width="80rpx">样品</uni-th>
											<uni-th align="left" width="200rpx">
												<view style="zoom: 0.8;">
													<text>下极限</text>
													<text style="margin: 0 4px;">/</text>
													<text>标准值</text>
													<text style="margin: 0 4px;">/</text>
													<text>上极限</text>
												</view>
											</uni-th>
											<uni-th align="left" width="100rpx">检验数据</uni-th>
											<uni-th align="left" width="100rpx">检验结果</uni-th>
											<uni-th align="left">检测工具</uni-th>
										</uni-tr>
										<!-- 表格数据行 -->
										<uni-tr
											v-for="(row,inx) in getFilterData(sample.ResultList,(ret,ind) => ind <=2 )"
											:key="index+'_'+sIndex+'_'+inx">
											<uni-td width="80rpx">{{row.YPMC}}</uni-td>
											<uni-td width="200rpx">
												<view class="x-sec" style="width: 100%;zoom: 0.8;">
													<text>{{row.PoorNormally || 'NaN'}}</text>
													<text>/</text>
													<text>{{row.JYBZ || 'NaN'}}</text>
													<text>/</text>
													<text>{{row.PoorWork || 'NaN'}}</text>
												</view>
											</uni-td>
											<uni-td width="100rpx">{{row.JYJG1 || '-'}}</uni-td>
											<uni-td width="100rpx">{{row.Result || '-'}}</uni-td>
											<uni-td>{{row.ApplianceTypeName}}</uni-td>
										</uni-tr>

									</uni-table>


								</template>
							</view>
						</view>
					</view>
				</view>
			</view>



		</view>

	</view>
</template>

<script setup lang="ts">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	let pageConfig = reactive<any>({
		titleName: "实验室检验明细",
		LabTestProductID: null
	})

	let formData = reactive<any>({
		ObjectName: '',
		BillNo: '',
		Inspection: '',
		InspectionPrice: '',
	})


	const processLabTestData = (data : any) => {
		const {
			ds1,
			ds2,
			ds3
		} = data;

		// ✅ 提前缓存 ds2 的 ID 列表，提升判断效率
		const ds2IdSet = new Set(ds2.map((item : any) => item.LabTestProductItemDeID));
		// 第一步：合并ds2和ds3为rootMap（修正版）
		const rootMap = new Map();

		[...ds2, ...ds3].forEach((item : any) => {
			const id = item.LabTestProductItemDeID;
			const isRoot = ds2IdSet.has(id); // 是否为ds2的主项（root）

			// 初始化rootMap：仅用ds2的项作为主项（无YPMC）
			if (isRoot && !rootMap.has(id)) {
				rootMap.set(id, {
					...item,
					ResultList: [] as any // 初始化空数组，用于存放ds3的关联项
				});
			}

			// 仅将ds3中含YPMC且关联ds2主项的项加入ResultList
			if (!isRoot) return; // 非ds2主项ID的项不处理
			if (item.YPMC) { // 若为ds3的项（含YPMC）且关联主项ID
				const rootItem = rootMap.get(id);
				rootItem.ResultList.push(item);
			}
		});

		// ✅ 获取合并后数组（保留属于 ds2 的主项）
		const mergedData = Array.from(rootMap.values()).filter(item =>
			ds2IdSet.has(item.LabTestProductItemDeID)
		);


		// ✅ 第二步：组装回 ds1 中，以 LabTestProductDeID 为关联键
		const resultData = JSON.parse(JSON.stringify(ds1));
		const processedMap = new Map();

		mergedData.forEach(item => {
			const key = item.LabTestProductDeID;
			if (!processedMap.has(key)) {
				processedMap.set(key, []);
			}
			processedMap.get(key).push(item);
		});

		resultData.forEach(item => {
			item.Details = processedMap.get(item.LabTestProductDeID) || [];
		});

		console.log(resultData);

		return resultData;
	}

	let tableData = ref<any>([]);
	// 用于存储每个样品表格的折叠状态
	let collapseStatus = ref<any>({});

	// 根据LabTestProductID获取页面信息
	const getPageInfoByID = () => {
		request({
			config: {},
			url: 'Qu_LabTestSelectDetails',
			method: 'POST',
			data: { LabTestProductID: pageConfig.LabTestProductID },
			success: async (ret : any) => {
				console.log(ret);
				if (ret.status == 200) {
					let {
						ds,
						ds1,
						ds2,
						ds3
					} = ret.data;

					if (ds.length) {
						Object.assign(formData, ds[0]);
					}

					let mergeData = processLabTestData({
						ds1,
						ds2,
						ds3
					});
					// 初始化折叠状态 - 默认全部折叠
					mergeData.forEach(item => {
						item.Details.forEach(sample => {
							let key = sample.LabTestProductItemDeID + '_' + sample
								.LabTestProjectID;

							collapseStatus.value[key] = true;
						});
					});

					tableData.value = mergeData;
				}
			}

		})
	};

	// 点击进入任务表格详情
	const openReportTable = (item : any) => {
		plus.screen.lockOrientation('landscape-primary');

		setTimeout(() => {
			uni.navigateTo({ // 前往表单界面 lucksheet
				url: '/st_qms/page_webview/webview_labreport' +
					'?keyID=' + item.LabTestProductID +
					'&keyDeID=' + item.LabTestProductDeID +
					'&MeasureTypeID=' + item.MeasureTypeID
			});
		}, 300)

	}

	const toggleCollapse = (key : any) => {
		// 如果是首次点击，初始化状态为展开（因为默认是折叠）
		if (uni.$utils.isEmpty(collapseStatus.value[key])) {
			collapseStatus.value[key] = false;
		} else {
			collapseStatus.value[key] = !collapseStatus.value[key];
		}
	}

	let moreListTableData = ref<any>([]);

	interface tableInterface {
		open : () => void;
		close : () => void;
	};
	let popup_table = ref<tableInterface | any>(null)
	const openMoreListTablePopup = (data : any) => {
		moreListTableData.value = data.ResultList;
		popup_table.value.open();
	};


	/**
		 * 过滤数组数据
		 * @param {Array} 过滤数组
		 * @param {Function} 过滤条件
		 * @return {Array} 返回过滤后的数据
		 */
	const getFilterData = (data : any[], filter : (ret : any, ind : any) => boolean) : any[] => {
		return data.filter(filter)
	}

	onLoad((option) => {
		pageConfig.LabTestProductID = option.LabTestProductID;
		getPageInfoByID();
	})
</script>

<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f9f9f9;

		&__main {

			.child-card {
				margin: 20rpx;
				padding: 20rpx;
				background-color: #fff;
				border-radius: 16rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

				&-top {
					display: flex;
					justify-content: space-between;
					align-items: center;

					&__left {
						display: flex;
						align-items: center;

						.ordinal {
							width: 40rpx;
							height: 40rpx;
							background: #007aff;
							color: #fff;
							border-radius: 50%;
							text-align: center;
							line-height: 40rpx;
							margin-right: 12rpx;
							font-size: 24rpx;
						}

						.title {
							font-size: 28rpx;
							font-weight: 600;
							color: #333;
						}
					}

					&__right {
						display: flex;
						align-items: center;
					}
				}

				.sample-list {
					margin-top: 16rpx;

					.sample-box {
						margin-top: 20rpx;
						border-top: 1rpx solid #eee;
						padding: 10rpx;
						border-radius: 10rpx;
						background-color: #eaf5f7;
						position: relative;

						.readMore {
							font-size: 12px;
							color: #4499ec;
							font-weight: 400;
							padding: 10px;
							position: absolute;
							top: 0;
							right: 0;
							min-width: 100px;
							height: 40px;
							line-height: 30px;
							// background-color: #40d37d;
							text-align: right;
						}

						.sample-scroll-list {
							background-color: #e8e8e8;
							padding: 10rpx;

							.sample-card {
								padding: 15rpx;
								background-color: #fff;
								min-width: 500rpx;
								min-height: 200rpx;
								margin: 10rpx;
								border-radius: 10rpx;
								zoom: 0.8;

								.sample-card__title {
									font-size: 28rpx;
									font-weight: 600;
									color: #3555ed;
									border-bottom: 1px solid #e8e8e8;
								}

								.sample-card__connect {
									padding: 10rpx 0;

									.result-bar {
										width: 100%;
										height: 30rpx;
										border-radius: 8rpx;
										background-size: 100% 100%;
										background-repeat: no-repeat;
										margin: 10rpx 0;
									}

									.sample-bottom {
										.sample-card__connect__cell {
											position: relative;
											padding-left: 20rpx !important;

											.sample-card__connect__cell-label {
												&::before {
													content: "";
													position: absolute;
													left: 0;
													top: 50%;
													transform: translateY(-50%);
													bottom: 0;
													width: 14rpx;
													height: 8rpx;
													border-radius: 1rpx;
												}

												&.green::before {
													background-color: #00c853;
												}

												&.red::before {
													background-color: #ff1744;
												}

												&.orange::before {
													background-color: #ffa000;
												}
											}
										}
									}

									.sample-card__connect__cell {
										padding: 8rpx 0;
										flex: 1;

										.sample-card__connect__cell-label {
											color: #949494;

										}

										.sample-card__connect__cell-value {
											flex: 1;
											color: #333;
											font-weight: 600;
											margin-left: 10rpx;
										}
									}
								}
							}
						}


						.sample-header {
							font-size: 26rpx;
							font-weight: bold;
							color: #333;
							margin-bottom: 10rpx;
						}

						.group-box {
							max-height: 300rpx;
							overflow-y: auto;
							background: #f9f9f9;
							border-radius: 10rpx;
							margin-top: 12rpx;
							padding: 16rpx;

							.group-header {
								font-size: 24rpx;
								margin-bottom: 10rpx;

								.group-title {
									font-weight: 600;
									color: #4863ff;
								}

								.group-stat {
									font-size: 22rpx;
									color: #888;
									margin-top: 4rpx;
									margin-left: 10rpx;
								}
							}

							.result-tag-list {
								display: flex;
								flex-wrap: wrap;
								gap: 12rpx;
								margin-top: 10rpx;
							}

							.result-tag {
								width: 20px;
								height: 20px;
								border-radius: 4px;
								font-size: 12px;
								font-weight: bold;
								color: #fff;
								text-align: center;
								line-height: 20px;

								&.ok {
									background-color: #4caf50; // 绿
								}

								&.fail {
									background-color: #f44336; // 红
								}

								&.pending {
									background-color: #ff9800; // 橙
								}
							}
						}
					}
				}
			}

		}
	}
</style>